package server

import (
	"net"
	"time"
)

type SessionBuilder struct {
	sessionHandle    ISessionHandle
	ReadIdleTimeout  time.Duration // 读空闲超时时间
	WriteIdleTimeout time.Duration // 写空闲超时时间
	IdleTimeout      time.Duration // 空闲超时时间
	WriteQueueSize   uint          // 读消息队列缓冲大小
	ReadQueueSize    uint          // 写消息队列缓冲大小
	ReadBuffer       uint          // 读缓冲字节大小
	coder            ICoder
}

func (x *SessionBuilder) SetCoder(coder ICoder) {
	x.coder = coder
}

func NewSessionBuilder(sessionHandle ISessionHandle) *SessionBuilder {
	return &SessionBuilder{
		sessionHandle: sessionHandle,
	}
}

func (x *SessionBuilder) Build() *Session {
	if x.sessionHandle == nil {
		panic("必须实现ISession接口")
	}

	if x.coder == nil {
		x.coder = &DefaultCoder{}
	}

	if x.ReadQueueSize == 0 {
		x.ReadQueueSize = 0xffff
	}

	if x.WriteQueueSize == 0 {
		x.WriteQueueSize = 0xffff
	}

	if x.ReadBuffer == 0 {
		x.ReadBuffer = 0xffff
	}

	session := &Session{
		conn:             nil,
		Server:           nil,
		SessionId:        0,
		sessionHandle:    x.sessionHandle,
		readIdleTimeout:  x.ReadIdleTimeout,
		writeIdleTimeout: x.WriteIdleTimeout,
		idleTimeout:      x.IdleTimeout,
		lastReadAt:       time.Time{},
		lastWriteAt:      time.Time{},
		lastActiveAt:     time.Time{},
	}
	return session
}

func BuildSession(server *Server, conn net.Conn) *Session {
	session := server.sessionBuilder.Build()
	session.conn = conn
	session.Server = server
	return session
}

func BuildUdpSession(server *Server, conn net.PacketConn, addr net.Addr) *Session {
	session := server.sessionBuilder.Build()
	session.packConn = conn
	session.udpAddr = addr
	session.Server = server
	return session
}
